﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebUI.Models;

namespace WebUI.Controllers
{
    public partial class Services
    {
        public Models.SiteDb DB { get; set; }
        public aspnet_Users SiteUser { get; set; }
        public static int DefaultPageSize = 25;
        //public System.Web.Mvc.IValueProvider ValueProvider { get; set; }
        //public System.Web.Mvc.ModelStateDictionary ModelState { get; set; }

        public _SiteBaseController ControllerContext{get;set;}
        /// <summary>
        /// for admin only
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public ListViewModel<CommonSearchValues, IQueryable<QizSession>> QizSessionList(ListViewModel<CommonSearchValues, IQueryable<QizSession>> m)
        {
            bool takeAll_forExport = false;
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<QizSession>>()
                {
                    PageIdx = 0,
                    PageSize = DefaultPageSize,
                    SearchFrom = new CommonSearchValues { V3 = string.Empty, V1 = string.Empty, V2 = string.Empty },
                    SearchTo = new CommonSearchValues { V3 = string.Empty }

                };
            }
            IQueryable<QizSession> d = null;
            if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Enginner" || v.RoleName == "Admin"))
            {
                d = DB.QizSessions.AsQueryable();
            }

            if (null != m.SearchFrom)
            {
                //if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1)) { d = d.Where(v => v.QizSubjectID == m.SearchFrom.V1); }
                if (string.IsNullOrWhiteSpace(m.SearchFrom.V1) || m.SearchFrom.V1 == "全部")
                    d = d.Where(v => v.QizSubject.SubjectType == null || v.QizSubject.SubjectType == "常规随访单");
                else
                    d = d.Where(v => v.QizSubjectID == m.SearchFrom.V1);

                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V4))
                {
                    string v4 = m.SearchFrom.V4;
                    var v4a = m.SearchFrom.V4.Split(':');

                    if (v4a.Length > 1)
                    {
                        v4 = v4a[1];
                        d = d.Where(v => v.QizSubject.ID == v4 || v.QizSubject.ParentQizSubject.ID == v4);
                    }
                    else
                    {
                        d = d.Where(v => v.QizSubjectID == v4 || v.QizSubject.Title.Contains(v4));// || v.QizSubject.ParentQizSubject.ID == v4 || v.QizSubject.ParentQizSubject.Title.Contains(v4));
                    }

                }
                if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { var o = Guid.Empty; Guid.TryParse(m.SearchFrom.V2, out o); d = d.Where(v => v.UserID == o || v.aspnet_Users.UserName.Contains(m.SearchFrom.V2)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = DateTime.Parse(m.SearchFrom.V3); d = d.Where(v => v.Timemark >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = DateTime.Parse(m.SearchTo.V3); d = d.Where(v => v.Timemark <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V5)) { d=d.Where(v=>v.TianBaoZhiLiang == m.SearchFrom.V5); }
            }
            d = d.OrderByDescending(v => v.CreationTime);
            m.ItemCount = d.Count();
            var ps = m.PageSize == 0 ? DefaultPageSize : m.PageSize;
            m.PageCount = (int)Math.Ceiling((double)d.Count() / ps);
            if (takeAll_forExport)
            {
                m.Data = d;
            }
            else
            {
                m.Data = d.Skip(ps * m.PageIdx).Take(ps);
            }

            return m;
        }


        /// <summary>
        /// takeAll_forExport=为导出数据，忽略分页，获取全部
        /// </summary>
        /// <param name="m"></param>
        /// <param name="takeAll_forExport">为导出数据，忽略分页，获取全部</param>
        /// <returns></returns>
        public ListViewModel<CommonSearchValues, IQueryable<QizSession>> QizSessionListForDoctor(ListViewModel<CommonSearchValues, IQueryable<QizSession>> m, bool takeAll_forExport = false)
        {
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<QizSession>>()
                {
                    PageIdx = 0,
                    PageSize = DefaultPageSize,
                    SearchFrom = new CommonSearchValues { V3 = string.Empty, V1 = string.Empty, V2 = string.Empty },
                    SearchTo = new CommonSearchValues { V3 = string.Empty }

                };
            }
            IQueryable<QizSession> d = null;
            if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Doctor"))
            {
                //d = DB.QizSessions.Where(v => v.QizSubject.QizSubjectObjForDoctors.Any(t => t.QizSubject.DepID == SiteUser.DepartmentID));
                d = DB.QizSessions.Where(v => v.QizSubject.QizSubjectObjForDoctors.Any(t => t.QizSubject.DepID == SiteUser.DepartmentID) || (v.ParentQizSession != null && v.ParentQizSession.QizSubject.QizSubjectObjForDoctors.Any(t => t.QizSubject.DepID == SiteUser.DepartmentID)));
            }
            else
            {
                d = DB.QizSessions.Where(v => v.UserID == SiteUser.UserId);
            }


            if (null != m.SearchFrom)
            {
                //bool withsubsubjs=(m.SearchTo.V1 == "1");

                //if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1) && m.SearchFrom.V1 != "全部")
                //{
                //    if (withsubsubjs) d = d.Where(v => v.QizSubjectID == m.SearchFrom.V1 || v.QizSubject.ParentQizSubject.ID == m.SearchFrom.V1);
                //    else  d = d.Where(v => v.QizSubjectID == m.SearchFrom.V1);

                //}
                //else if (!withsubsubjs)  d = d.Where(v => v.QizSubject.SubjectType == null || v.QizSubject.SubjectType == "常规随访单");


                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1) && m.SearchFrom.V1 != "全部")
                {
                    if (m.SearchTo.V1 == "1") d = d.Where(v => v.QizSubjectID == m.SearchFrom.V1 || v.QizSubject.ParentQizSubject.ID == m.SearchFrom.V1);
                    else if (m.SearchTo.V1 == "2") d = d.Where(v => (v.QizSubjectID == m.SearchFrom.V1 || v.QizSubject.ParentQizSubject.ID == m.SearchFrom.V1) && (v.QizSubject.SubjectType == "指标库"));
                    else d = d.Where(v => v.QizSubjectID == m.SearchFrom.V1);

                }
                else if (m.SearchTo.V1 == "2") d = d.Where(v => v.QizSubject.SubjectType == "指标库");
                else if (m.SearchTo.V1 != "1") d = d.Where(v => v.QizSubject.SubjectType == null || v.QizSubject.SubjectType == "常规随访单");
                //else .. all. not filter any thing.


                if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { d = d.Where(v => v.aspnet_Users.UserName.Contains(m.SearchFrom.V2)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = DateTime.Parse(m.SearchFrom.V3); d = d.Where(v => v.Timemark >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = DateTime.Parse(m.SearchTo.V3); d = d.Where(v => v.Timemark <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V4) && m.SearchFrom.V4 != "全部") { var o = Guid.Parse(m.SearchFrom.V4); d = d.Where(v => v.Recuper.DoctorID == o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V5) && m.SearchFrom.V5 != "全部") { d = d.Where(v => v.Recuper.User.Gender == m.SearchFrom.V5); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V6)) { var o = DateTime.Parse(m.SearchFrom.V6); d = d.Where(v => v.Recuper.DeHospDay >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V6)) { var o = DateTime.Parse(m.SearchTo.V6); d = d.Where(v => v.Recuper.DeHospDay <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V0)) { d = d.Where(v => v.Recuper.SuiFangLeiXing.Contains(m.SearchFrom.V0)); }
                if (!string.IsNullOrEmpty(m.SearchTo.V0)) { d = d.Where(v => v.TianBaoZhiLiang.Contains(m.SearchTo.V0)); }
                if (!string.IsNullOrEmpty(m.SearchTo.V4)) { d = d.Where(v => v.Recuper.ZhenDuanS.Contains(m.SearchTo.V4)); }
                if (!string.IsNullOrEmpty(m.SearchTo.V5)) { d = d.Where(v => v.Recuper.ShouShuS.Contains(m.SearchTo.V5)); }
            }

            var ps = m.PageSize == 0 ? DefaultPageSize : m.PageSize;
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / ps);

            d = d.OrderByDescending(v => v.CreationTime);
            if (takeAll_forExport)
            {
                m.Data = d;
            }
            else
            {
                m.Data = d.Skip(ps * m.PageIdx).Take(ps);
            }
            return m;
        }
        /// <summary>
        /// 作了另一种尝试，但性能一样不好。
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public ListViewModel<CommonSearchValues, IQueryable<QizSessionDetail>> QizSessionListForDoctor_Detail(ListViewModel<CommonSearchValues, IQueryable<QizSessionDetail>> m)
        {
            var takeAll_forExport = true;
            DB.CommandTimeout = 600;

            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<QizSessionDetail>>()
                {
                    PageIdx = 0,
                    PageSize = DefaultPageSize,
                    SearchFrom = new CommonSearchValues { V3 = string.Empty, V1 = string.Empty, V2 = string.Empty },
                    SearchTo = new CommonSearchValues { V3 = string.Empty }

                };
            }
            IQueryable<QizSessionDetail> d = null;
            if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Doctor"))
            {
                d = DB.QizSessionDetails
                    .Include("QizSession")
                    .Include("QizSession.Recuper")
                    .Include("QizSession.Recuper.User")
                    .Where(v => 
                        v.QizSession.QizSubject.QizSubjectObjForDoctors.Any(t => t.QizSubject.DepID == SiteUser.DepartmentID) || (v.QizSession.ParentQizSession != null && v.QizSession.ParentQizSession.QizSubject.QizSubjectObjForDoctors.Any(t => t.QizSubject.DepID == SiteUser.DepartmentID)));
            }
            else
            {
                d = DB.QizSessionDetails
                    .Include("QizSession")
                    .Include("QizSession.Recuper")
                    .Include("QizSession.Recuper.User")
                    .Where(v => v.QizSession.UserID == SiteUser.UserId);
            }


            if (null != m.SearchFrom)
            {
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1) && m.SearchFrom.V1 != "全部") { d = d.Where(v => v.QizSession.QizSubjectID == m.SearchFrom.V1); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { d = d.Where(v => v.QizSession.aspnet_Users.UserName.Contains(m.SearchFrom.V2)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = DateTime.Parse(m.SearchFrom.V3); d = d.Where(v => v.QizSession.Timemark >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = DateTime.Parse(m.SearchTo.V3); d = d.Where(v => v.QizSession.Timemark <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V4) && m.SearchFrom.V4 != "全部") { var o = Guid.Parse(m.SearchFrom.V4); d = d.Where(v => v.QizSession.Recuper.DoctorID == o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V5) && m.SearchFrom.V5 != "全部") { d = d.Where(v => v.QizSession.Recuper.User.Gender == m.SearchFrom.V5); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V6)) { var o = DateTime.Parse(m.SearchFrom.V6); d = d.Where(v => v.QizSession.Recuper.DeHospDay >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V6)) { var o = DateTime.Parse(m.SearchTo.V6); d = d.Where(v => v.QizSession.Recuper.DeHospDay <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V0)) { d = d.Where(v => v.QizSession.Recuper.SuiFangLeiXing.Contains(m.SearchFrom.V0)); }
            }

            var ps = m.PageSize == 0 ? DefaultPageSize : m.PageSize;
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / ps);

            d = d.OrderByDescending(v => v.QizSession.Timemark);
            if (takeAll_forExport)
            {
                m.Data = d;
            }
            else
            {
                m.Data = d.Skip(ps * m.PageIdx).Take(ps);
            }
            return m;

        }
        /// <summary>
        /// 性能不佳
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public ListViewModel<CommonSearchValues, IQueryable<QizSessionDetail>> QizSessionListForDoctor_Detail(ListViewModel<CommonSearchValues, IQueryable<QizSession>> m)
        {
            DB.CommandTimeout = 600;
            var sd = QizSessionListForDoctor(m, true);
            var r = sd.Data.SelectMany(v => v.QizSessionDetails.Where(t=>t.UserValue!=null&&t.UserValue!=""));
            return new ListViewModel<CommonSearchValues, IQueryable<QizSessionDetail>>()
            {
                ItemCount = r.Count(),
                PageCount = 1,
                PageIdx = 0,
                PageSize = r.Count(),
                SearchFrom = sd.SearchFrom,
                SearchTo = sd.SearchTo,
                Tag = sd.Tag,
                Data = r
            };

        }
        public ListViewModel<CommonSearchValues, IQueryable<QizSession>> QizSessionListForRecuper(ListViewModel<CommonSearchValues, IQueryable<QizSession>> m)
        {
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<QizSession>>()
                {
                    PageIdx = 0,
                    PageSize = DefaultPageSize,
                    SearchFrom = new CommonSearchValues { V3 = string.Empty, V1 = string.Empty, V2 = string.Empty },
                    SearchTo = new CommonSearchValues { V3 = string.Empty }

                };
            }
            IQueryable<QizSession> d = null;

            d = DB.QizSessions.Where(v => v.UserID == SiteUser.UserId);// && (v.QizSubject.SubjectType == "常规随访单" || v.QizSubject.SubjectType == null)
            //d = DB.QizSessions.Where(v => v.UserID == SiteUser.UserId);
            if (null != m.SearchFrom)
            {
                //if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1)) { d = d.Where(v => v.QizSubjectID == m.SearchFrom.V1); }
                
                if (string.IsNullOrWhiteSpace(m.SearchFrom.V1) || m.SearchFrom.V1 == "全部")
                     d = d.Where(v => v.QizSubject.SubjectType == null || v.QizSubject.SubjectType == "常规随访单");
                else
                    d = d.Where(v => v.QizSubjectID == m.SearchFrom.V1);


                if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = DateTime.Parse(m.SearchFrom.V3); d = d.Where(v => v.Timemark >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = DateTime.Parse(m.SearchTo.V3); d = d.Where(v => v.Timemark <= o); }
            }

            var ps = m.PageSize == 0 ? DefaultPageSize : m.PageSize;
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / ps);
            d = d.OrderByDescending(v => v.CreationTime).ThenBy(v => v.QizSubjectID);
            m.Data = d.Skip(ps * m.PageIdx).Take(ps);

            return m;
        }

        public ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> QizSmsSessionListForAdmin(ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> m)
        {
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>>()
                {
                    PageIdx = 0,
                    PageSize = DefaultPageSize,
                    SearchFrom = new CommonSearchValues { V3 = string.Empty, V1 = string.Empty, V2 = string.Empty },
                    SearchTo = new CommonSearchValues { V3 = string.Empty }

                };
            }
            IQueryable<QizSmsSession> d = null;
            if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Enginner" || v.RoleName == "Admin"))
            {
                d = DB.QizSmsSessions.AsQueryable();
            }
            else if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Recuper"))
            {
                d = DB.QizSmsSessions.Where(v => v.Recuper.UserID == SiteUser.UserId);
            }
            d = d.Where(v=>v.SessionStatus==3);
            if (null != m.SearchFrom)
            {
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1)) { d = d.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubjectID == m.SearchFrom.V1); }
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V4))
                {
                    string v4 = m.SearchFrom.V4;
                    var v4a = m.SearchFrom.V4.Split(':');

                    if (v4a.Length > 1)
                    {
                        v4 = v4a[1];
                        d = d.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubject.ID == v4);
                    }
                    else
                    {
                        d = d.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubjectID == v4 || v.QizSmsSubjectMonthIdx.QizSmsSubject.Title.Contains(v4));
                    }

                }
                if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { var o = Guid.Empty; Guid.TryParse(m.SearchFrom.V2, out o); d = d.Where(v => v.UserID == o || v.User.UserName.Contains(m.SearchFrom.V2)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = DateTime.Parse(m.SearchFrom.V3); d = d.Where(v => v.Timemark >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = DateTime.Parse(m.SearchTo.V3); d = d.Where(v => v.Timemark <= o); }
            }

            var ps = m.PageSize == 0 ? DefaultPageSize : m.PageSize;
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / ps);
            d = d.OrderByDescending(v => v.CreationTime);
            m.Data = d.Skip(ps * m.PageIdx).Take(ps);

            return m;
        }

        /// <summary>
        /// takeAll_forExport=为导出数据，忽略分页，获取全部
        /// </summary>
        /// <param name="m"></param>
        /// <param name="takeAll_forExport">为导出数据，忽略分页，获取全部</param>
        /// <returns></returns>
        public ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> QizSmsSessionListForDoctor(ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> m, bool takeAll_forExport = false)
        {
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>>()
                {
                    PageIdx = 0,
                    PageSize = DefaultPageSize,
                    SearchFrom = new CommonSearchValues { V3 = string.Empty, V1 = string.Empty, V2 = string.Empty },
                    SearchTo = new CommonSearchValues { V3 = string.Empty }

                };
            }
            IQueryable<QizSmsSession> d = null;
            if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Doctor"))
            {
                if (SiteUser.IsDoctorDepManager)
                {
                    d = DB.QizSmsSessions.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubjectObjForDoctors.Any(t => t.QizSubject.DepID == SiteUser.DepartmentID));
                    //d = DB.QizSessionDetails.Where(v => v.QizSession.QizSubject.QizSubjectObjForDoctors.Any(t => t.QizSubject.DepID == SiteUser.DepartmentID));
                }
                else
                {
                    d = DB.QizSmsSessions.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubjectObjForDoctors.Any(t => t.DoctorID == SiteUser.UserId));
                    //d = DB.QizSessionDetails.Where(v => v.QizSession.QizSubject.QizSubjectObjForDoctors.Any(t => t.DoctorID == SiteUser.UserId));
                }
            }
            d = d.Where(v=>v.SessionStatus==3);
            if (null != m.SearchFrom)
            {
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1)) { d = d.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubject.ID == m.SearchFrom.V1); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { d = d.Where(v => v.Recuper.User.UserName.Contains(m.SearchFrom.V2)); }

                if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = DateTime.Parse(m.SearchFrom.V3); d = d.Where(v => v.Timemark >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = DateTime.Parse(m.SearchTo.V3); d = d.Where(v => v.Timemark <= o); }
            }

            var ps = m.PageSize == 0 ? DefaultPageSize : m.PageSize;
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / ps);
            d = d.OrderByDescending(v => v.CreationTime).ThenBy(v => v.QizSmsSubjectMonthIdx.QizSmsSubject.ID);
            if (takeAll_forExport)
            {
                m.Data = d;
            }
            else
            {
                m.Data = d.Skip(ps * m.PageIdx).Take(ps);
            }


            return m;
        }
        public ListViewModel<CommonSearchValues, IQueryable<QizSmsSessionDetail>> QizSmsSessionListForDoctor_Detail(ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> m)
        {
            var sd = QizSmsSessionListForDoctor(m, true);
            var r = sd.Data.SelectMany(v => v.QizSmsSessionDetails);
            return new ListViewModel<CommonSearchValues, IQueryable<QizSmsSessionDetail>>()
            {
                ItemCount = r.Count(),
                PageCount = 1,
                PageIdx = 0,
                PageSize = r.Count(),
                SearchFrom = sd.SearchFrom,
                SearchTo = sd.SearchTo,
                Tag = sd.Tag,
                Data = r
            };

        }
        public ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> QizSmsSessionListForRecuper(ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> m)
        {
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>>()
                {
                    PageIdx = 0,
                    PageSize = DefaultPageSize,
                    SearchFrom = new CommonSearchValues { V3 = string.Empty, V1 = string.Empty, V2 = string.Empty },
                    SearchTo = new CommonSearchValues { V3 = string.Empty }

                };
            }
            IQueryable<QizSmsSession> d = null;

            d = DB.QizSmsSessions.Where(v => v.UserID == SiteUser.UserId);
            d = d.Where(v => v.SessionStatus == 3);


            if (null != m.SearchFrom)
            {
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1)) { d = d.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubjectID == m.SearchFrom.V1); }

                if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = DateTime.Parse(m.SearchFrom.V3); d = d.Where(v => v.Timemark >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = DateTime.Parse(m.SearchTo.V3); d = d.Where(v => v.Timemark <= o); }
            }

            var ps = m.PageSize == 0 ? DefaultPageSize : m.PageSize;
            m.ItemCount = d.Count();

            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / ps);
            d = d.OrderBy(v => v.QizSmsSubjectMonthIdx.QizSmsSubjectID).ThenByDescending(v => v.Timemark);
            m.Data = d.Skip(ps * m.PageIdx).Take(ps);

            return m;
        }


        public ListViewModel<CommonSearchValues2, IQueryable<Recuper>> RecuperListForDoctor(ListViewModel<CommonSearchValues2, IQueryable<Recuper>> m, bool takeAll_forExport = false)
        {
            IQueryable<Recuper> d = DB.Recupers.Where(v => v.DepartmentID == SiteUser.DepartmentID).AsQueryable();
            if (m != null && m.SearchFrom != null)
            {
                if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { d = d.Where(v => v.User.UserName.Contains(m.SearchFrom.V1)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { d = d.Where(v => v.User.Gender == m.SearchFrom.V2); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = int.Parse(m.SearchFrom.V3); d = d.Where(v => v.BingAnHao >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = int.Parse(m.SearchTo.V3); d = d.Where(v => v.BingAnHao <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V4)) { d = d.Where(v => v.User.MobileAlias.Contains(m.SearchFrom.V4)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V5)) { var o = DateTime.Parse(m.SearchFrom.V5); d = d.Where(v => v.User.BirthDay >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V5)) { var o = DateTime.Parse(m.SearchTo.V5); d = d.Where(v => v.User.BirthDay <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V6)) { var o = Guid.Parse(m.SearchFrom.V6); d = d.Where(v => v.DoctorID == o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V7)) { var o = DateTime.Parse(m.SearchFrom.V7); d = d.Where(v => v.EnHospDay >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V7)) { var o = DateTime.Parse(m.SearchTo.V7); d = d.Where(v => v.EnHospDay <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V8)) { d = d.Where(v => v.ZhenDuanS.Contains(m.SearchFrom.V8)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V9)) { var o = DateTime.Parse(m.SearchFrom.V9); d = d.Where(v => v.DeHospDay >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V9)) { var o = DateTime.Parse(m.SearchTo.V9); d = d.Where(v => v.DeHospDay <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V10)) { d = d.Where(v => v.ShouShuS.Contains(m.SearchFrom.V10)); }
                if (!string.IsNullOrWhiteSpace(m.SearchTo.V6)) { d = d.Where(v => v.SuiFangLeiXing.Contains(m.SearchTo.V6)); }
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V11)) 
                {
                    if (m.SearchFrom.V11 == "已出院")
                    {
                        d = d.Where(v => v.DeHospDay!=DateTime.MinValue && v.DeHospDay <= DateTime.Now);
                    }
                    else if(m.SearchFrom.V11 == "未出院")
                    {
                        d = d.Where(v => v.DeHospDay == DateTime.MinValue || v.DeHospDay > DateTime.Now);
                    }
                }
                if (!string.IsNullOrEmpty(m.SearchFrom.V12) && m.SearchFrom.V12 != "全部")
                {
                    if (m.SearchFrom.V12 == "已参与")
                    {
                        d = d.Where(v => (v.QizSessions.Count(s => s.QizSubject.SubjectType == "常规随访单") + v.QizSmsSessions.Count(j=>j.SessionStatus==3)) > 0);
                    }
                    else if (m.SearchFrom.V12 == "未参与")
                    {
                        d = d.Where(v => (v.QizSessions.Count(s => s.QizSubject.SubjectType == "常规随访单") + v.QizSmsSessions.Count(j => j.SessionStatus == 3)) == 0);
                    }
                }
                //added by wkwang 2014/3/31
                if (!string.IsNullOrEmpty(m.SearchTo.V10))
                {
                    if (m.SearchTo.V10 == "可发起随访")
                    {
                        d = d.Where(v => !v.GuoQi);
                    }
                    else if (m.SearchTo.V10 == "不发起随访")
                    {
                        d = d.Where(v => v.GuoQi);
                    }
                }
                //if (null != exp) d = d.Where(exp);
            }
            else
            {
                m = new ListViewModel<CommonSearchValues2, IQueryable<Recuper>>();
                m.SearchFrom = new CommonSearchValues2();
                m.SearchTo = new CommonSearchValues2();
            }
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / m.PageSize);

            //d = d.OrderBy(v => v.User.UserName);
            if (string.IsNullOrEmpty(m.SortOrder)) m.SortOrder = "Asc";
            var isSortAsc = (m.SortOrder == "Asc");
            if (string.IsNullOrEmpty(m.SortBy)) m.SortBy = "出院时间";
            if (m.SortBy == "年龄")
            {
                d = isSortAsc ? d.OrderBy(v => v.User.BirthDay) : d.OrderByDescending(v=>v.User.BirthDay);
            }
            else if (m.SortBy == "姓名") {
                d = isSortAsc ? d.OrderBy(v => v.User.UserName) : d.OrderByDescending(v=>v.User.UserName);
            }
            else
            {
                d = isSortAsc ? d.OrderByDescending(v => v.DeHospDay) : d.OrderBy(v => v.DeHospDay);
            }
            //if (!isSortAsc) m.SortOrder = string.Empty;//this mean sortasc
            //else m.SortOrder = m.SortBy;

            if (takeAll_forExport)
            {
                m.Data = d;
            }
            else
            {
                m.Data = d.Skip(m.PageIdx * m.PageSize).Take(m.PageSize);
            }
            return m;
        }

        public ListViewModel<CommonSearchValues2, IQueryable<Recuper>> SubjectRecuperListForDoctor(string SubjectID, bool IsContain, ListViewModel<CommonSearchValues2, IQueryable<Recuper>> m, bool takeAll_forExport = false)
        {
            var d = DB.Recupers.Where(s => s.DepartmentID == SiteUser.DepartmentID && !s.GuoQi && s.DeHospDay != DateTime.MinValue).AsQueryable();
            if (m != null && m.SearchFrom != null)
            {
                if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { d = d.Where(v => v.User.UserName.Contains(m.SearchFrom.V1)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { d = d.Where(v => v.User.Gender == m.SearchFrom.V2); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = int.Parse(m.SearchFrom.V3); d = d.Where(v => v.BingAnHao >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = int.Parse(m.SearchTo.V3); d = d.Where(v => v.BingAnHao <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V4)) { d = d.Where(v => v.User.MobileAlias.Contains(m.SearchFrom.V4)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V5)) { var o = DateTime.Parse(m.SearchFrom.V5); d = d.Where(v => v.User.BirthDay >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V5)) { var o = DateTime.Parse(m.SearchTo.V5); d = d.Where(v => v.User.BirthDay <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V6)) { d = d.Where(v => v.SuiFangLeiXing.Contains(m.SearchFrom.V6)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V7)) { var o = DateTime.Parse(m.SearchFrom.V7); d = d.Where(v => v.EnHospDay >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V7)) { var o = DateTime.Parse(m.SearchTo.V7); d = d.Where(v => v.EnHospDay <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V8)) { d = d.Where(v => v.ZhenDuanS.Contains(m.SearchFrom.V8)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V9)) { var o = DateTime.Parse(m.SearchFrom.V9); d = d.Where(v => v.DeHospDay >= o); }
                if (!string.IsNullOrEmpty(m.SearchTo.V9)) { var o = DateTime.Parse(m.SearchTo.V9); d = d.Where(v => v.DeHospDay <= o); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V10)) { d = d.Where(v => v.ShouShuS.Contains(m.SearchFrom.V10)); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V11)) { d = d.Where(v => v.Doctor.UserName == m.SearchFrom.V11); }
                if (!string.IsNullOrEmpty(m.SearchFrom.V12)) { d = d.Where(s=>s.QizSubjectObjForDoctors.Any(q => q.QizSubjectID == SubjectID && q.QizSmsSubjectID==m.SearchFrom.V12));}
            }
            else
            {
                m = new ListViewModel<CommonSearchValues2, IQueryable<Recuper>>();
                m.SearchFrom = new CommonSearchValues2();
                m.SearchTo = new CommonSearchValues2();
                m.Tag = new CommonSearchValues2() { V1 = SubjectID };

            }
            if (IsContain)
            {
                d = d.Where(s => s.QizSubjectObjForDoctors.Any(q => q.QizSubjectID == SubjectID));
            }
            else
            {
                d = d.Where(s => !s.QizSubjectObjForDoctors.Any(q => q.QizSubjectID == SubjectID));
            }

            //d = d.OrderBy(v => v.User.UserName);
            if (string.IsNullOrEmpty(m.SortOrder)) m.SortOrder = "Asc";
            var isSortAsc =( m.SortOrder == "Asc");
            if (string.IsNullOrEmpty(m.SortBy)) m.SortBy = "出院时间";
            if (m.SortBy == "年龄")
            {
                d = isSortAsc ? d.OrderBy(v => v.User.BirthDay) : d.OrderByDescending(v => v.User.BirthDay);
            }
            else if (m.SortBy == "姓名")
            {
                d = isSortAsc ? d.OrderBy(v => v.User.UserName) : d.OrderByDescending(v => v.User.UserName);
            }
            else if (IsContain && m.SortBy == "参加日期")
            {                
                d = isSortAsc ? d.OrderBy(v => v.QizSubjectObjForDoctors.FirstOrDefault(q=>q.QizSubjectID == SubjectID).Timemark)
                    : d.OrderByDescending(v => v.QizSubjectObjForDoctors.FirstOrDefault(q => q.QizSubjectID == SubjectID).Timemark);
            }
            else
            {
                d = isSortAsc ? d.OrderByDescending(v => v.DeHospDay) : d.OrderBy(v => v.DeHospDay);
            }

            //if (!isSortAsc) m.SortOrder = string.Empty;//this mean sortasc
            //else m.SortOrder = m.SortBy;

            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / m.PageSize);

            if (takeAll_forExport)
            {
                m.Data = d;
            }
            else
            {
                m.Data = d.Skip(m.PageIdx * m.PageSize).Take(m.PageSize);
            }
            return m;
        }

        public void SessionEvalStatusNotify(QizSmsSession session)
        {
            //session.User.MainRoleNam
            //var dm=session.Department.aspnet_Users.Where(v => v.IsDoctorDepManager).FirstOrDefault();
            //foreach此subject此患者的每个医生的 正 异提醒
            var subjectForDoctor = session.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.QizSubjectObjForDoctors.FirstOrDefault(v => v.RecuperID == session.RecuperID);
            if (subjectForDoctor != null)
            //foreach (var item in session.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.QizSubjectObjForDoctors.Where(v=>v.RecuperID == session.UserID))
            {
                var item = session.QizSmsSubjectMonthIdx.QizSmsSubject;
                var s = (session.SessionAutoEvalution == "异常") ? item.MsgTemplateForBad : item.MsgTemplateForFine;
                //s = s.Replace("{医院}", item.Doctor.Hospital.HospName).Replace("{科室}", item.Doctor.Department.DepName);//TODO more //{医院}、{科室}、{医生、医生电话、主治医生、主治医生电话 ,,主治稍难
                SmsSent sms = new SmsSent();
                sms.ID = DB.NewID();
                sms.ReceiverCode = session.User.MobileAlias;//item.Recuper.User.MobileAlias; //invite.Recuper.User.MobileAlias;
                sms.ReceiverName = session.User.UserName; //item.Recuper.User.UserName;
                sms.SentTime = DateTime.Now;
                sms.ProcTime = DateTime.Now;
                sms.SmsType = "结果评价";
                sms.ProcStatus = "发送";
                sms.SenderCode = subjectForDoctor.Doctor.UserId.ToString(); //item.Doctor.MobileAlias;
                sms.SenderName = subjectForDoctor.Doctor.UserName;//TODO more //{医院}、{科室}、{医生、医生电话、主治医生、主治医生电话 ,,主治稍难,{随访}
                sms.TextMessage = SmsMessageAutoReplace(s, subjectForDoctor.Doctor.Hospital.HospName, subjectForDoctor.Doctor.Department.DepName, subjectForDoctor.Doctor.UserName,
                    item.QizSubject.Title, subjectForDoctor.Doctor.MobileAlias, subjectForDoctor.Recuper.Doctor.UserName, subjectForDoctor.Recuper.Doctor.MobileAlias);
                DB.SmsSents.AddObject(sms);
            }
            DB.SaveChanges();
        }


        public void AddToSubjectNotify(List<QizSubjectObjForDoctor> invites)
        {
            foreach (var invite in invites)
            {

                SmsSent sms = new SmsSent();
                sms.ID = DB.NewID();
                sms.ReceiverCode = invite.Recuper.User.MobileAlias;
                sms.ReceiverName = invite.Recuper.User.UserName;
                sms.SentTime = DateTime.Now;
                sms.ProcTime = DateTime.Now;
                sms.ProcStatus = "发送";
                sms.SmsType = "随访邀请";
                sms.SenderCode = invite.Doctor.UserId.ToString();
                sms.SenderName = invite.Doctor.UserName;//TODO more //{医院}、{科室}、{医生}、{医生电话}、{主治医生}、{主治医生电话} ,,主治稍难,{课题}
                sms.TextMessage = SmsMessageAutoReplace(invite.QizSmsSubject.RecuperInvitMsg, invite.Doctor.Hospital.HospName, invite.Doctor.Department.DepName,
                    invite.Doctor.UserName, invite.QizSubject.Title, invite.Doctor.MobileAlias, invite.Recuper.Doctor.UserName, invite.Recuper.Doctor.MobileAlias);
                //sms.TextMessage = invite.QizSmsSubject.RecuperInvitMsg.Replace("{医院}", invite.Doctor.Hospital.HospName).Replace(
                //    "{科室}", invite.Doctor.Department.DepName).Replace("{医生}", invite.Doctor.UserName).Replace(
                //    "{随访}", invite.QizSubject.Title).Replace("{患者}", invite.Recuper.User.UserName);
                DB.SmsSents.AddObject(sms);
            }
            DB.SaveChanges();
        }

        public Models.QizSession RecuperSummaryReportOfMonthIdx(string[] UserID, int MonthIdx, string QizSmsSubjectID)
        {
            var recu = DB.Recupers.FirstOrDefault(v => UserID.Contains(v.RecuperID));
            var smssubj = DB.QizSmsSubjects.FirstOrDefault(v => v.ID == QizSmsSubjectID);

            var dehostday = new DateTime(recu.DeHospDay.Year, recu.DeHospDay.Month, 1);
            var midxobj = smssubj.QizSmsSubjectMonthIdxes.First(v => v.MonthIdx == MonthIdx);
            var qizsubjectid = smssubj.SubjectID;
            var lastmonth = dehostday.AddMonths(midxobj.LastMonthIdx);
            var nextmonth = dehostday.AddMonths(midxobj.MonthIdx);


            var qizsession = DB.QizSessions.Where(v => UserID.Contains(v.RecuperID) && v.QizSubjectID == qizsubjectid && v.Timemark > lastmonth && v.Timemark <= nextmonth).OrderByDescending(v => v.Timemark).FirstOrDefault();
            if (qizsession == null)
            {
                qizsession = new QizSession() { QizSubject = smssubj.QizSubject, ID = string.Empty };
                foreach (var qizdef in smssubj.QizSubject.QizSubjectDefines)
                {
                    qizdef.QizSessionDetails.Add(new QizSessionDetail() { ID = qizdef.ID, QizSession = qizsession, QizSubjectDefine = qizdef });
                }
            }
            var smssession = midxobj.QizSmsSessions.FirstOrDefault(v => UserID.Contains(v.RecuperID));
            if (null != smssession)
            {
                foreach (var ssd in smssession.QizSmsSessionDetails)
                {
                    if (ssd.Timemark > qizsession.Timemark)
                    {
                        var qsd = qizsession.QizSessionDetails.First(v => v.QizSubjectDefID == ssd.QizSmsSubjDefine.QizSubjDefID);
                        qsd.UserValue = ssd.UserValue;
                        qsd.UserSelValue = ssd.UserSelValueID;
                        qsd.ValueAutoEvaluation = ssd.ValueAutoEvalution;
                    }
                }

            }
            return qizsession;


        }
        public SortedList<int, List<Tuple<int, string, string>>> RecuperSummaryReport(string[] UserID, int MonthIdx, string QizSmsSubjectID)
        {
            var recu = DB.Recupers.FirstOrDefault(v => UserID.Contains(v.RecuperID));

            var smssubj = DB.QizSmsSubjects.FirstOrDefault(v => v.ID == QizSmsSubjectID);
            SortedList<int, List<Tuple<int, string, string>>> data = new SortedList<int, List<Tuple<int, string, string>>>();
            if (null == smssubj)
            {
                data.Add(0, new List<Tuple<int, string, string>>());
            }
            else
            {
                var dehostday = recu.DeHospDay;
                dehostday = new DateTime(dehostday.Year, dehostday.Month, 1);
                var lastmonth = dehostday;//new DateTime(dehostday.Year, dehostday.Month, 1);// dehostday.AddDays(-dehostday.Day);
                var midxs = smssubj.QizSmsSubjectMonthIdxes.AsQueryable();
                if (MonthIdx != 0)
                {
                    midxs = midxs.Where(v => v.MonthIdx == MonthIdx);
                }
                midxs = midxs.OrderBy(v => v.MonthIdx);

                data.Add(0,
                    smssubj.QizSubject.QizSubjectDefines.OrderBy(v => v.SortIdx).Select(v => new Tuple<int, string, string>(v.SortIdx, v.QizItem.Type, v.QizItem.Title)).ToList()
                );

                foreach (var midx in midxs)
                {
                    if (lastmonth > DateTime.Now) break;
                    DateTime nextmonth = dehostday.AddMonths(midx.MonthIdx);

                    List<Tuple<int, string, string>> values = null;

                    var qizsession = DB.QizSessions.Where(v => UserID.Contains(v.RecuperID) && v.QizSubjectID == smssubj.SubjectID && v.Timemark >= lastmonth && v.Timemark < nextmonth).OrderByDescending(v => v.Timemark).FirstOrDefault();
                    if (null != qizsession)
                    {
                        values = qizsession.QizSessionDetails.OrderBy(v => v.QizSubjectDefine.SortIdx).Select(v => new Tuple<int, string, string>(v.QizSubjectDefine.SortIdx, v.UserValue, v.QizSubjectDefine.QizItem.TypeRef.OptionValue)).ToList();
                    }
                    else
                    {
                        values = smssubj.QizSubject.QizSubjectDefines.OrderBy(v => v.SortIdx).Select(v => new Tuple<int, string, string>(v.SortIdx, string.Empty, string.Empty)).ToList();
                    }
                    var smssession = midx.QizSmsSessions.FirstOrDefault(v => UserID.Contains(v.RecuperID));
                    if (null != smssession)
                    {

                        foreach (var ssd in smssession.QizSmsSessionDetails)
                        {
                            if (qizsession == null || ssd.Timemark > qizsession.Timemark)
                            {

                                var sdidx = values.IndexOf(values.FirstOrDefault(v => v.Item1 == ssd.QizSmsSubjDefine.QizSubjectDefine.SortIdx));
                                values[sdidx] = new Tuple<int, string, string>(ssd.QizSmsSubjDefine.QizSubjectDefine.SortIdx, ssd.UserValue, ssd.UserSelValueID);
                            }
                        }

                    }
                    data.Add(midx.MonthIdx, values);
                    lastmonth = nextmonth;
                }

            }
            return data;
        }
        public string SmsMessageAutoReplace(string message, string hospital, string dep, string doctor, string subject, string doctorPhone, string chargeDoctor, string chargeDoctorPhone)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                return null;
            }
            else
            {
                return message.Replace("{医院}", hospital).Replace("{科室}", dep).Replace("{随访}", subject).Replace("{医生}", doctor).Replace(
                    "{医生电话}", doctorPhone).Replace("{主管医生}", chargeDoctor).Replace("{主管医生电话}", chargeDoctorPhone);
            }
        }


        public ListViewModel<CommonSearchValues, IQueryable<T>> ParseListViewModeJsonFilter<T>(string CurrentFilterOfJson)
        {
            return ParseListViewModeJsonFilterEx<CommonSearchValues, T>(CurrentFilterOfJson);
        }
        public ListViewModel<M, IQueryable<T>> ParseListViewModeJsonFilterEx<M, T>(string CurrentFilterOfJson)
        {
            var tm = System.Web.Helpers.Json.Decode<ListViewModel<M, string>>(CurrentFilterOfJson);
            ListViewModel<M, IQueryable<T>> m = new ListViewModel<M, IQueryable<T>>()
            {
                SearchFrom = tm.SearchFrom,
                SearchTo = tm.SearchTo
            };
            return m;
        }

        public string DepartmentProfileSettingArrayEditor(string sk,string newValuesString,bool SaveDb=false) {
            string r = newValuesString;
            if (!string.IsNullOrEmpty(newValuesString))
            {
                var sa = newValuesString.Split(',');
                var zls = SiteUser.Department.DepartmentProfiles.Where(v => v.SettingKey == sk).ToList();
                var tbzl = string.Empty;
                foreach (var si in sa)
                {
                    var s = si.Replace('\'', '’');
                    if (s.StartsWith("-"))
                    {
                        var p = zls.FirstOrDefault(v => v.SettingValue == s.Substring(1));
                        if (null != p) DB.DepartmentProfiles.DeleteObject(p);
                    }
                    else
                    {
                        tbzl += s + ",";
                        var p = zls.FirstOrDefault(v => v.SettingValue == s);
                        if (null == p) DB.DepartmentProfiles.AddObject(new DepartmentProfile() { ID = DB.NewID(), DepartmentID = SiteUser.DepartmentID, SettingKey = sk, SettingValue = s, SortIdx = 0, Timemark = DateTime.Now });
                    }
                }
                r = tbzl.TrimEnd(','); 
            }
            else
            {
                r = string.Empty;
            }
            if (SaveDb) DB.SaveChanges();
            return r;
        }
        //public SortedList<int, List<Tuple<int, string, string, string, DateTime>>> RecuperSummaryReport(string recuperID, string qizSubjectID, int pageIndex)
        //{
        //    var recu = DB.Recupers.FirstOrDefault(v => recuperID == v.RecuperID);

        //    var smssubj = DB.QizSmsSubjects.FirstOrDefault(v => v.SubjectID == qizSubjectID);
        //    var subj = DB.QizSubjects.FirstOrDefault(v => v.ID == qizSubjectID);
        //    SortedList<DateTime, List<Tuple<int, string, string, string, DateTime>>> data = new SortedList<DateTime, List<Tuple<int, string, string, string, DateTime>>>();
        //    var sessions = DB.QizSessionDetails.Where(s =>
        //        s.QizSubjectDefine.QizSubjectID == qizSubjectID
        //        && s.QizSession.RecuperID == recuperID);
        //    List<QizSession> allSession = new List<QizSession>();

        //    var sessions = DB.QizSessions.Where(s =>
        //        s.QizSubjectID == qizSubjectID
        //        && s.RecuperID == recuperID);
        //    foreach (var session in sessions)
        //    {
        //        allSession.Add(session);
        //    }


        //    var smsSessions = DB.QizSmsSessions.Where(s =>
        //        s.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.ID == qizSubjectID
        //        && s.RecuperID == recuperID
        //        && s.SessionStatus == 3);
        //    foreach (var session in smsSessions)
        //    {
        //        QizSession smsSession = new QizSession();
        //        smsSession.Timemark = session.Timemark;
        //        smsSession.Recuper = session.Recuper;
        //        smsSession.QizSubject = session.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject;
        //        smsSession.QizSubjectID = session.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.ID;
        //        List<Tuple<int, string, string, string, DateTime>> netList = new List<Tuple<int, string, string, string, DateTime>>();
        //        smsSession.QizSessionDetails = new System.Data.Objects.DataClasses.EntityCollection<QizSessionDetail>();
        //        foreach (var detail in session.QizSmsSessionDetails)
        //        {
        //            QizSessionDetail qizDetail = new QizSessionDetail();
        //            qizDetail.UserValue = detail.UserValue;
        //            var tempData = new Tuple<int, string, string, string, DateTime>(
        //                    detail.QizSmsSubjDefine.QizSubjectDefine.QizItem.SortIdx.Value,
        //                    detail.QizSmsSubjDefine.QizSubjectDefine.QizItem.Title,
        //                    detail.UserValue,
        //                    "短信",
        //                session.Timemark);

        //            netList.Add(tempData);
        //            netList.OrderBy(s => s.Item1).ToList();
        //            smsSession.QizSessionDetails.Add(qizDetail);
        //        }
        //        allSession.Add(smsSession);
        //    }
        //    allSession.AsQueryable();
        //}
        //public ListViewModel<CommonSearchValues, IQueryable<QizSmsSessionDetail>> QizSmsSessionList(ListViewModel<CommonSearchValues, IQueryable<QizSmsSessionDetail>> m)
        //{
        //    if (null == m || null == m.SearchFrom)
        //    {
        //        m = new ListViewModel<CommonSearchValues, IQueryable<QizSmsSessionDetail>>()
        //        {
        //            PageIdx = 0,
        //            PageSize = DefaultPageSize,
        //            SearchFrom = new CommonSearchValues { V3 = string.Empty, V1 = string.Empty, V2 = string.Empty },
        //            SearchTo = new CommonSearchValues { V3 = string.Empty }

        //        };
        //    }
        //    IQueryable<QizSmsSessionDetail> d = null;
        //    if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Enginner" || v.RoleName == "Admin"))
        //    {
        //        d = DB.QizSmsSessionDetails.AsQueryable();
        //    }
        //    else if (SiteUser.aspnet_Roles.Any(v => v.RoleName == "Doctor"))
        //    {
        //        //if (SiteUser.IsDoctorDepManager)
        //        //{
        //        d = DB.QizSmsSessionDetails.Where(v => v.QizSmsSession.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.QizSubjectObjForDoctors.Any(t => t.QizSubject.DepID == SiteUser.DepartmentID));
        //        //}
        //        //else
        //        //{
        //        //    d = DB.QizSmsSessionDetails.Where(v => v.QizSmsSession.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.QizSubjectObjForDoctors.Any(t => t.DoctorID == SiteUser.UserId));
        //        //}
        //    }
        //    else
        //    {
        //        d = DB.QizSmsSessionDetails.Where(v => v.QizSmsSession.UserID == SiteUser.UserId);
        //    }


        //    if (null != m.SearchFrom)
        //    {
        //        if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1)) { d = d.Where(v => v.QizSmsSession.QizSmsSubjectMonthIdx.QizSmsSubjectID == m.SearchFrom.V1); }
        //        if (!string.IsNullOrWhiteSpace(m.SearchFrom.V4))
        //        {
        //            string v4 = m.SearchFrom.V4;
        //            var v4a = m.SearchFrom.V4.Split(':');

        //            if (v4a.Length > 1)
        //            {
        //                v4 = v4a[1];
        //                d = d.Where(v => v.QizSmsSession.QizSmsSubjectMonthIdx.QizSmsSubject.ID == v4);
        //            }
        //            else
        //            {
        //                d = d.Where(v => v.QizSmsSession.QizSmsSubjectMonthIdx.QizSmsSubjectID == v4 || v.QizSmsSession.QizSmsSubjectMonthIdx.QizSmsSubject.Title.Contains(v4));
        //            }

        //        }
        //        if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { var o = Guid.Empty; Guid.TryParse(m.SearchFrom.V2, out o); d = d.Where(v => v.QizSmsSession.UserID == o || v.QizSmsSession.User.UserName.Contains(m.SearchFrom.V2)); }
        //        if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { var o = DateTime.Parse(m.SearchFrom.V3); d = d.Where(v => v.QizSmsSession.Timemark >= o); }
        //        if (!string.IsNullOrEmpty(m.SearchTo.V3)) { var o = DateTime.Parse(m.SearchTo.V3); d = d.Where(v => v.QizSmsSession.Timemark <= o); }
        //    }

        //    var ps = m.PageSize == 0 ? DefaultPageSize : m.PageSize;
        //    m.ItemCount = d.Count();
        //    m.PageCount = (int)Math.Ceiling((double)m.ItemCount / ps);
        //    d = d.OrderBy(v => v.QizSmsSession.QizSmsSubjectMonthIdx.QizSmsSubjectID).ThenBy(v => v.QizSmsSession.UserID).ThenBy(v => v.QizSmsSubjDefine.QizSubjectDefine.SortIdx).ThenByDescending(v => v.QizSmsSession.Timemark);
        //    m.Data = d.Skip(ps * m.PageIdx).Take(ps);

        //    return m;
        //}

        public void UpdateRecuperAttachInfo(Recuper recuper)
        {
            string RecuperAttachInfoPrefixs = ControllerContext.Request["RecuperAttachPrefixs"];
            if (String.IsNullOrEmpty(RecuperAttachInfoPrefixs))
            {
                return;
            }
            string[] prefixs = RecuperAttachInfoPrefixs.Split(',');
            if (prefixs == null || prefixs.Length == 0)
            {
                return;
            }
            System.Text.StringBuilder errorMessages = new System.Text.StringBuilder();
            foreach (string prefix in prefixs)
            {
                string departProfilesId = ControllerContext.Request[prefix + "_DepartProfilesID"];
                string title = ControllerContext.Request[prefix + "_AttachTitle"];
                string value = ControllerContext.Request[prefix + "_AttachValue"];
                DepartmentProfile profile = DB.DepartmentProfiles.SingleOrDefault(p => p.ID == departProfilesId);
                if (profile == null)
                {
                    errorMessages.AppendLine(String.Format("定制属性“{0}”已被删除！", title));
                }
                else
                {
                    int maxLength = Convert.ToInt32(profile.SettingValueC);
                    if (maxLength > 0)
                    {
                        if (value.Length > maxLength)
                        {
                            errorMessages.AppendLine(String.Format("定制属性“{0}”的长度不能超过{1}个字符！", title, maxLength));
                        }
                    }
                }
                if (errorMessages.Length > 0)
                {
                    continue;
                }
                RecuperAttachInfo attach = null;
                string idFromRequest = ControllerContext.Request[prefix + "_ID"];
                attach = DB.RecuperAttachInfos.SingleOrDefault(a => a.ID == idFromRequest);
                if (attach == null)
                {
                    attach = new RecuperAttachInfo
                    {
                        ID = DB.NewID(),//如果是新添加的属性，ID是一个临时的GUID，保存时需要重新生成
                        DepartProfilesID = departProfilesId,
                        RecuperID = recuper.RecuperID,
                        AttachTitle = title,
                        AttachValue = value
                    };
                    DB.RecuperAttachInfos.AddObject(attach);
                }
                else
                {
                    attach.AttachValue = value;
                }                
            }
            if (errorMessages.Length > 0)
            {
                throw new SiteException(errorMessages.ToString());
            }
        }
    }
}
